package com.yhy.common.vo;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

/**
 * <br>
 * <b>功能：</b>排序bean<br>
 * <b>作者：</b>yanghuiyuan<br>
 */
public class OrderVO implements Serializable {
    public static final String ASC = "asc";
    public static final String DESC = "desc";

    private String[] sortFields = new String[0];
    private String[] sortTypes = new String[0];

    /**
     * 排序字段
     */
    protected String orderBy = null;

    public String[] getSortFields() {
        return sortFields;
    }

    public void setSortFields(String[] sortFields) {
        this.sortFields = sortFields;
    }

    public String[] getSortTypes() {
        return sortTypes;
    }

    public void setSortTypes(String[] sortTypes) {
        this.sortTypes = sortTypes;
    }

    /**
     * 设置排序字段,多个排序字段时用','分隔.
     */
    public void setSortField(final String sortField) {
        if (StringUtils.isNotBlank(sortField)) {
            sortFields = sortField.split(",");
        }
    }


    /**
     * 设置排序方式向.
     */
    public void setOrder(final String order) {
        if (StringUtils.isNotBlank(order)) {
            String lowcaseOrder = order.toLowerCase();

            //检查order字符串的合法值
            String[] orders = lowcaseOrder.split(",");
            for (String orderStr : orders) {
                if (!DESC.equals(orderStr) && !ASC.equals(orderStr)) {
                    throw new IllegalArgumentException("排序值非法" + orderStr);
                }
            }
            sortTypes = orders;
        }
    }

    public String getOrderBy() {
        if (orderBy == null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < sortFields.length; i++) {
                String sortFiled = sortFields[i];
                sb.append(sortFiled);
                if (i <= sortTypes.length - 1) {
                    sb.append(" ").append(sortTypes[i]);
                }
                if (i != sortFields.length - 1) {
                    sb.append(",");
                }
            }
            orderBy = StringUtils.defaultIfBlank(sb.toString(), "");
        }
        return orderBy;
    }

}
